import {
  Component,
  OnInit,
  AfterViewInit,
  ChangeDetectorRef,
  ChangeDetectionStrategy,
  ViewChild,
  ElementRef,
  Injectable
} from '@angular/core';
import { fromEvent, Observable, of } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, pluck, retry, switchMap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';

@Injectable()
class WikeService {
  readonly url = 'http://www.codeman.ink/api/search/suggest?keywords=';
  list(keyword): Observable<any> {
    return ajax.getJSON(this.url + keyword).pipe(map(res => res));
  }
}

@Component({
  selector: 'app-test-rx',
  template: `
    <div class="autocomplete">
      <input #input class="form-control" placeholder="search..." />
      <ul class="list-group mt-2">
        <li class="list-group-item" *ngFor="let item of result.order">{{ item }}</li>
      </ul>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [WikeService]
})
export class TestRxComponent implements OnInit, AfterViewInit {
  result = {};
  @ViewChild('input', { static: true }) private inputEle: ElementRef;
  constructor(private wikeService: WikeService, private cdr: ChangeDetectorRef) {
    // this.wikeService.list('a').subscribe(res => {
    //   console.log('res:', res);
    // });
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    fromEvent(this.inputEle.nativeElement, 'input')
    .pipe(debounceTime(500), pluck('target', 'value'), distinctUntilChanged(), switchMap((value: string) => {
      return value.length ? this.wikeService.list(value) : of([]);
    }), retry(3))
    .subscribe(res => {
      console.log('res:', res);
      this.result = res;
      this.cdr.markForCheck();
    });
  }
}
